const employeeService = require('../services/employeeService');
const { StatusCodes } = require('http-status-codes');
const Joi = require('joi');

// 验证规则
const employeeSchema = Joi.object({
  name: Joi.string().required().min(2).max(50),
  phone: Joi.string().required().pattern(/^[0-9]{10,15}$/),
  position: Joi.string().required().valid('cashier', 'manager', 'stock_keeper', 'other'),
  store_id: Joi.number().integer().allow(null),
  hire_date: Joi.date().allow(null),
  status: Joi.string().valid('active', 'inactive').default('active')
});

// 状态更新验证规则
const statusSchema = Joi.object({
  status: Joi.string().required().valid('active', 'inactive')
});

class EmployeeController {
  async createEmployee(req, res, next) {
    try {
      // 验证请求体
      const { error, value } = employeeSchema.validate(req.body);
      if (error) {
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const employee = await employeeService.createEmployee(value);
      res.status(StatusCodes.CREATED).json(employee);
    } catch (err) {
      next(err);
    }
  }

  async getEmployee(req, res, next) {
    try {
      const employee = await employeeService.getEmployeeById(req.params.id);
      res.status(StatusCodes.OK).json(employee);
    } catch (err) {
      next(err);
    }
  }

  async getAllEmployees(req, res, next) {
    try {
      const { status, store_id } = req.query;
      const employees = await employeeService.getAllEmployees({ status, store_id });
      res.status(StatusCodes.OK).json(employees);
    } catch (err) {
      next(err);
    }
  }

  async updateEmployee(req, res, next) {
    try {
      // 验证请求体
      const { error, value } = employeeSchema.validate(req.body);
      if (error) {
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const employee = await employeeService.updateEmployee(req.params.id, value);
      res.status(StatusCodes.OK).json(employee);
    } catch (err) {
      next(err);
    }
  }

  async updateEmployeeStatus(req, res, next) {
    try {
      console.log('更新员工状态请求:', req.body); // 添加日志
      const { error, value } = statusSchema.validate(req.body);
      if (error) {
        console.error('状态验证错误:', error.details); // 添加日志
        return res.status(StatusCodes.BAD_REQUEST).json({
          error: error.details[0].message
        });
      }

      const employee = await employeeService.updateEmployeeStatus(req.params.id, value.status);
      res.status(StatusCodes.OK).json(employee);
    } catch (err) {
      console.error('更新员工状态错误:', err); // 添加日志
      next(err);
    }
  }

  async deleteEmployee(req, res, next) {
    try {
      await employeeService.deleteEmployee(req.params.id);
      res.status(StatusCodes.NO_CONTENT).send();
    } catch (err) {
      next(err);
    }
  }
}

module.exports = new EmployeeController();